package com.lrm.web.admin;

import com.lrm.biz.ITagBiz;
import com.lrm.pojo.Tag;
import com.lrm.util.Result;
import com.lrm.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2017/11/30.
 * @Modified By:
 */
@RestController
@RequestMapping("admin")
public class TagController {

    @Autowired
    private ITagBiz ITagBiz;

    /**
     * 分页查询列表并，默认是10条，并按ID倒序排列
     * @param pageable
     * @return
     */
    @GetMapping("listTagPages")
    public Result listPages(@PageableDefault(size = 10,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable){
        Page<Tag> Tags = ITagBiz.pagelistTag(pageable);
        return ResultUtil.success(Tags);
    }

    @PostMapping("addTag")
    public Result addTag(@Valid Tag tag){
        Tag byname = ITagBiz.findByname(tag.getName());
        if (byname!=null) {
            return ResultUtil.error(2,"类型已存在，不能重复添加");
        }
        Tag Tag1 = ITagBiz.saveTag(tag);
        if (Tag1==null) {
            return ResultUtil.error(2,"保存失败");
        }
        return ResultUtil.success(Tag1);
    }

    @GetMapping("delTag/{id}")
    public Result delTag(@PathVariable Long id){
        Boolean b = ITagBiz.delTag(id);
        if (b) {
            return ResultUtil.success();
        }
        return ResultUtil.error(2,"删除失败");
    }

    @PostMapping("updataTag/{id}")
    public Result updataTag(@PathVariable Long id,@Valid Tag tag){
        Tag byname = ITagBiz.findByname(tag.getName());
        if (byname!=null) {
            return ResultUtil.error(2,"标签已存在，不能重复添加");
        }
        Tag Tag1 = ITagBiz.upadtaTag(id, tag);
        if (Tag1!=null) {
            return ResultUtil.success(Tag1);
        }
        return ResultUtil.error(2,"修改失败");
    }
}
